package session

import (
	"net/http"
)

type Session struct {
	sessionId	string
	sessions  	*sessions
	request     *http.Request
	response    http.ResponseWriter
}

func (s *Session) ID() string {
	return s.sessionId
}

func (s *Session) Get(key string) interface{} {
	return s.sessions.Store.Get(s.ID(), key)
}

func (s *Session) Set(key string, value interface{}) {
	s.sessions.Store.Set(s.ID(), key, value)
}

func (s *Session) Del(key string) error {
	return s.sessions.Store.Del(s.ID(), key)
}

func (s *Session) Exist() bool {
	return s.sessions.exist(s.ID())
}

func (s *Session) Clear() error {
	if err := s.sessions.Provider.Del(s.response, s.request); err != nil {
		return err
	}
	return s.sessions.Store.Clear(s.ID())
}

func (s *Session) start() error {
	sessionId, err := s.sessions.Provider.Get(s.response, s.request)
	if err != nil {
		return err
	}

	if !validateSessionID(sessionId) {
		sessionId, _ = createSessionID()
		s.sessions.Store.Set(sessionId, "", nil)
		s.sessions.Provider.Set(s.response, s.request, sessionId)
	}

	s.sessionId = sessionId

	return nil
}

func Start(w http.ResponseWriter, r *http.Request) (*Session, error) {
	session := &Session{sessions: Manager(), response: w, request:  r}
	if err := session.start(); err != nil {
		return nil, err
	}
	return session, nil
}